//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;

        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}

document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    // 模拟点击第一个带有 active 类的导航链接
    const activeLink = document.querySelector('.nav-link.active');
    if (activeLink) {
        const targetId = activeLink.dataset.target;
        const targetContent = document.getElementById(targetId);
        navLinks.forEach(navLink => navLink.classList.remove('active'));
        contentAreas.forEach(content => content.classList.remove('active'));
        activeLink.classList.add('active');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            contentAreas.forEach(content => content.classList.remove('active'));
            this.classList.add('active');
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });
    $(document).ready(function () {
        const rowsPerPage = 4; // 每页显示的行数，需与后端默认 pageSize 一致
        const $tableBody = $('#categoryList');
        const $pageNav = $('#pageNav');
        let currentPage = 1;
        let totalPages = 1;

        $tableBody.on('click', '.deletebtn, .editbtn', function(event) {
            const $btn = $(event.target);
            const action = $btn.attr('class').split(' ')[0];
            const id = $btn.closest('tr').data('id');

            switch (action) {
                case 'deletebtn': // 删除按钮
                    handleDeleteUser($btn, id);
                    break;
                case 'editbtn': // 编辑按钮
                    handleEditUser(this);
                    break;
            }
        });

        // 初始化加载第一页数据
        loadPage(1);

        // 加载指定页数据
        function loadPage(pageNumber) {
            currentPage = pageNumber;

            $.ajax({
                type: 'GET',
                url: '/admin/getCategoriesFromManagerWithPaging', // 后端分页接口
                data: {
                    pageNum: pageNumber,
                    pageSize: rowsPerPage
                },
                success: function (response) {
                    console.log('后端返回数据:', response);
                    const CateList = response.list || [];
                    totalPages = response.totalPage || 1;

                    $tableBody.empty();
                    if (CateList.length > 0) {
                        CateList.forEach(cate => {
                            const row = $('<tr>')
                                .attr('data-id',cate.id)
                                .append(`
                                <td><input type="checkbox" class="rowCheckbox" data-id="${cate.id}"></td>
                                <td class="title-cell">${cate.name}</td> <!-- 使用cate.name -->
                                <td>
                                    <div class="contents" style="max-width: 170px;">${cate.description}</div> <!-- 使用cate.description -->
                                </td>
                                <td>
                                    <button class="editbtn text-xl" data-id="${cate.id}">编辑</button>
                                    <button class="deletebtn" data-id="${cate.id}">删除</button>
                                </td>
                            `);
                            $tableBody.append(row);
                        });
                        initSelectAll();
                        $pageNav.show();
                    } else {

                        $pageNav.hide();
                    }

                    updatePagination();
                },
                error: function (error) {
                    console.error('分页数据加载失败:', error);

                    $pageNav.hide();
                }
            });
            //查询
            $('#checkkey-button').click(function() {
                const searchTerm = $('#check').val();
                if (searchTerm.trim()!== '') {
                    console.log("页数为："+currentPage);
                    // 发送AJAX请求
                    $.ajax({
                        type: 'GET',
                        url: '/admin/behindManagerCategory', // 后端查询用户的API
                        data: { query: searchTerm,
                            pageNum: currentPage
                        },
                        success: function(response) {
                            // 清空表格
                            $('#categoryList').empty();
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response, 'text/html');

                            // 获取搜索关键词（转为小写用于不区分大小写匹配）
                            const searchTerm = $('#check').val().trim().toLowerCase();

                            // 从HTML中提取用户行，并过滤包含关键词的行
                            const Rows = Array.from(doc.querySelectorAll('#categoryList tr:not(thead tr)'))
                                .filter(row => {
                                    // 获取用户名单元格内容（第3列）
                                    const titleCell = row.querySelector('td:nth-child(2)');
                                    return titleCell && titleCell.textContent.toLowerCase().includes(searchTerm);
                                });

                            if (Rows.length === 0) {
                                const notice=document.getElementById('notice');
                                notice.style.display='block';
                                return;
                            }else{
                                const notice=document.getElementById('notice');
                                notice.style.display='none';
                            }

                            console.log(0);
                            // 遍历过滤后的行并添加到表格
                            Rows.forEach(row => {
                                const userId = row.getAttribute('data-id') || row.getAttribute('th:data-id');
                                const cells = row.querySelectorAll('td');
                                const newRow = $('<tr>')
                                    .attr('data-id', userId)
                                    .append(`<td><input type="checkbox" class="rowCheckbox" data-id="${userId}"></td>`)
                                    .append(`<td>${cells[1].textContent}</td>`)
                                    .append(`<td>${cells[2].textContent}</td>`)
                                    .append(`<td>
                       <button class="editbtn text-xl" data-id="${userId}">编辑</button>
                         <button class="deletebtn" data-id="${userId}">删除</button>
                            </td>`);
                                console.log(21);
                                console.log(newRow);
                                $('#categoryList').append(newRow);
                            });
                        },
                        error: function(error) {
                            console.error('查询失败', error);
                            showCustomAlert('查询失败，请稍后重试',3000);
                        }
                    });
                } else {
                    showCustomAlert('请输入查询关键词',3000);
                }
            });
        }
        function initSelectAll() {
            const selectAll = document.querySelector('.selectAll');
            const rowCheckboxes = document.querySelectorAll('.rowCheckbox');

            // 清除旧事件（防止重复绑定）
            if (selectAll) {
                selectAll.removeEventListener('change', handleSelectAll);
                selectAll.addEventListener('change', handleSelectAll);
            }

            rowCheckboxes.forEach(checkbox => {
                checkbox.removeEventListener('change', handleRowCheckbox);
                checkbox.addEventListener('change', handleRowCheckbox);
            });
        }

// 全选事件处理函数
        function handleSelectAll() {
            const isChecked = this.checked;
            document.querySelectorAll('.rowCheckbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
        }

// 行复选框事件处理函数
        function handleRowCheckbox() {
            const allChecked = document.querySelectorAll('.rowCheckbox:checked').length ===
                document.querySelectorAll('.rowCheckbox').length;
            document.querySelector('.selectAll').checked = allChecked;
        }

        // 更新分页导航
        function updatePagination() {
            $pageNav.empty(); // 清空原有导航

            // 上一页按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
                $prevBtn.addClass('disabled'); // 第一页时禁用
            } else {
                $prevBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 页码按钮（显示当前页附近的页码）
            const maxVisiblePages = 4;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 左侧省略号
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            // 页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active'); // 高亮当前页
                } else {
                    $pageBtn.click(function (e) {
                        e.preventDefault();
                        loadPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 右侧省略号
            if (endPage < totalPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 下一页按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === totalPages) {
                $nextBtn.addClass('disabled'); // 最后一页时禁用
            } else {
                $nextBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }
    });
});

function handleDeleteUser($btn, id) {
    confirms('确定要删除该类别吗？', (isConfirmed) => {
        if (isConfirmed) {
            $.ajax({
                url: `/admin/toDeleteCategory?id=${id}`, // 直接将ID作为查询参数
                method: 'GET', // 保持与后端一致
                success: function (response) {
                    // 成功后刷新页面或移除当前行
                    $btn.closest('tr').remove();
                    location.reload();
                    showCustomAlert('删除成功',3000);
                },
                error: function (error) {
                    console.error('删除失败:', error);
                    showCustomAlert('删除失败，请重试',3000);
                }
            });
        }
    })
}
// 批量删除功能（适配单接口）
const deleteAll = document.getElementById("check-button");
deleteAll.addEventListener('click', function () {
    const checkedBoxes = $('.rowCheckbox:checked');

    if (checkedBoxes.length === 0) {
        showCustomAlert('请先选择要删除的类别',3000);
        return;
    }
    confirms(`确定要删除选中的 ${checkedBoxes.length} 个类别吗？`, (isConfirmed) => {
        if (!isConfirmed) {
            return;
        }
    // 逐个调用单个删除接口
    let deletedCount = 0;
    const ids = checkedBoxes.map(function () {
        return $(this).data('id'); // 直接获取复选框的data-user-id（需确保HTML中存在）
    }).get();
    // 禁用按钮防止重复提交
    $(this).prop('disabled', true).text('删除中...');

    // 循环发送请求（使用async/await处理异步流程）
    (async function () {
        try {
            for (const id of ids) {
                // 调用单个删除接口
                const response = await $.ajax({
                    url: `http://localhost:8080/admin/toDeleteCategory`,
                    method: 'GET',
                    data: {id: id},
                    dataType: 'text'
                });
                deletedCount++;
                // 移除对应的表格行
                $(`tr[data-user-id="${id}"]`).remove();
                console.log(id);
                location.reload();

            }
            showCustomAlert(`成功删除 ${deletedCount} 个类别`,3000);
        } catch (error) {
            console.error('批量删除失败:', error);
            showCustomAlert(`删除过程中出错，已成功删除 ${deletedCount} 个类别，剩余操作未完成`,3000);
        } finally {
            // 恢复按钮状态
            $('#check-button').prop('disabled', false).text('全部删除');
        }
    })();
});
});


const categoryEditModal = document.getElementById('categoryEditModal');
const categoryEditModalSaveButton = document.getElementById('categoryEditModalSaveButton');
let currentCategoryId = null; // 存储当前编辑的类别ID

// 类别编辑按钮事件处理
const editButtons = document.querySelectorAll('.editbtn');
let currentEditRow;
function openModalAndFillData(modalId, button) {
    const modal = document.getElementById(modalId);
    modal.style.display = 'block';
    const currentRow = button.closest('tr');
    return currentRow;
}
function handleEditUser(button) {
    currentEditRow = openModalAndFillData('categoryEditModal', button);
    if (!currentEditRow) {
        showCustomAlert('未找到对应的表格行',3000);
        return;
    }

    currentCategoryId = button.getAttribute('data-id'); // 从按钮获取 data-id
    if (!currentCategoryId) {
        showCustomAlert('分类ID缺失',3000);
        return;
    }

    // 填充数据
    try {
        const name = currentEditRow.querySelector('td:nth-child(2)').textContent.trim();
        const contentDiv = currentEditRow.querySelector('td:nth-child(3) .contents');
        const content = contentDiv ? contentDiv.innerHTML.trim() : '';

        document.getElementById('categoryKindInput').value = name;
        document.getElementById('categoryEditPostContentDiv').innerHTML = content;
    } catch (error) {
        console.error('数据填充失败:', error);
        showCustomAlert('数据填充失败，请检查表格结构',3000);
    }
}

// 模态框保存按钮的事件处理（独立函数）
document.getElementById('categoryEditModalSaveButton').addEventListener('click', function() {
    if (!currentCategoryId || !currentEditRow) {
        showCustomAlert('请选择要编辑的分类',3000);
        return;
    }

    const newName = document.getElementById('categoryKindInput').value.trim();
    const newContent = document.getElementById('categoryEditPostContentDiv').innerHTML.trim();

    // 发送 AJAX 请求
    $.ajax({
        url: `http://localhost:8080/admin/toUpdateCategory`,
        method: 'POST',
        data: {
            id: currentCategoryId,
            name: newName,
            description: newContent
        },
        success: function(response) {
            if (response.success) {
                // 更新表格数据
                currentEditRow.querySelector('td:nth-child(2)').textContent = newName;
                currentEditRow.querySelector('td:nth-child(3)').innerHTML = `<div class="contents">${newContent}</div>`;

                // 隐藏模态框
                document.getElementById('categoryEditModal').style.display = 'none';
                showCustomAlert('更新成功',3000);
            } else {
                showCustomAlert(`更新失败: ${response.message}`,3000);
            }
        },
        error: function(error) {
            console.error('请求失败:', error);
            showCustomAlert('服务器错误，请重试',3000);
        }
    });
});

// 返回表单
const backform = document.getElementById('backform');
backform.addEventListener('click', function () {
    location.reload();
});


// 为所有取消按钮添加点击事件
const cancelEditPostButtons = document.querySelector('.cancelEditPost');
const cancelEditPostButtons1 = document.querySelector('.cancelEditPost1');
const addModal1 = document.getElementById('addModal1');
const addModal = document.getElementById('categoryEditModal');
cancelEditPostButtons1.addEventListener('click',function(){
    addModal1.style.display = 'none';
    // 清空输入
    categoryNameInput.value = '';
    categoryContentInput.innerHTML = '';
    nameError.textContent = '';
    contentError.textContent = '';
})
cancelEditPostButtons.addEventListener('click',function(){
    addModal.style.display = 'none';
});
    //添加

    // 获取元素
    const addBtn = document.getElementById('addButton1'); // 假设你的添加按钮类名为 add-button
    const saveButton = document.getElementById('categoryEditModalSaveButton1');
    const cancelButton = document.querySelector('.cancelEditPost');
    const categoryNameInput = document.getElementById('categoryKindInput1');
    const categoryContentInput = document.getElementById('categoryEditPostContentDiv1');

// 错误提示元素
    const nameError = document.getElementById('categoryNameError');
    const contentError = document.getElementById('categoryContentError');

// 打开模态框
    addBtn.addEventListener('click', () => {
        addModal1.style.display = 'block';
        // 清空输入
        categoryNameInput.value = '';
        categoryContentInput.innerHTML = '';
        nameError.textContent = '';
        contentError.textContent = '';
    });
// 表单验证函数
    function validateForm() {
        let isValid = true;
        const name = document.getElementById('categoryKindInput1').value;
        const description = document.getElementById('categoryEditPostContentDiv1').textContent;

        // 校验类别名称
        if (name === '') {
            nameError.textContent = '类别名称不能为空';
            isValid = false;
        } else if (name.length > 20) {
            nameError.textContent = '类别名称不能超过20个字符';
            isValid = false;
        } else {
            nameError.textContent = '';
        }

        // 校验内容
        if (description === '') {
            contentError.textContent = '类别内容不能为空';
            isValid = false;
        } else {
            contentError.textContent = '';
        }

        return isValid;
    }

// 保存按钮点击事件
    saveButton.addEventListener('click', () => {

        console.log("添加")
        const name = document.getElementById('categoryKindInput1').value;
        const description = document.getElementById('categoryEditPostContentDiv1').textContent;

        const filteredname = name.replace(/<[^>]*>/g, '');
        const filtereddescription = description.replace(/<[^>]*>/g, '');

        if (!validateForm()) return; // 校验不通过，终止操作

        var params = $.param({
            name:filteredname,
            description: filtereddescription,
        });

        // 发送 AJAX 请求
        $.ajax({
            type: 'POST',
            url: `http://localhost:8080/admin/toInsertCategory`, // 替换为实际接口
            data: params,
            success: function (response) {
                location.reload();
                 addModal.style.display = 'none';
                showCustomAlert('添加成功',3000);
            },
            error: function (error) {
                console.error('服务器错误:', error);
                showCustomAlert('添加失败，请检查网络或联系管理员',3000);
            }
        });
    });
    cancelButton.addEventListener('click',function(){
        addModal.style.display = 'none';
        categoryNameInput.value = '';
        categoryContentInput.innerHTML = '';
});